NestJS swagger Cheatsheet
README
이 문서는 @ApiTags
, @ApiBearerAuth
등과 같은 다양한 데코레이터 함수들을 정리하고 치트시트처럼 사용하기 위해 만들어졌습니다.
Installation
npm install --save @nestjs/swagger swagger-ui-express
Basic Setup
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('API Documentation')
.setDescription('API description')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
Swagger Decorators
@ApiTags
Defines a tag for grouping related endpoints in Swagger UI.
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
@ApiTags('Users')
@Controller('users')
export class UserController {
@Get()
findAll() {
return ['User1', 'User2'];
}
}
@ApiOperation
Adds metadata to describe an endpoint operation.
import { ApiOperation } from '@nestjs/swagger';
@Get()
@ApiOperation({ summary: 'Retrieve all users', description: 'Returns a list of users' })
findAll() {
return ['User1', 'User2'];
}
@ApiBody
Defines the expected request body schema.
import { ApiBody } from '@nestjs/swagger';
@Post()
@ApiBody({
schema: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
},
},
})
create(@Body() body: any) {
return body;
}
@ApiBearerAuth
Adds authentication information in Swagger UI.
import { ApiBearerAuth } from '@nestjs/swagger';
@ApiBearerAuth()
@Get('profile')
getProfile() {
return { user: 'John Doe' };
}
@ApiOkResponse
Describes a successful response.
import { ApiOkResponse } from '@nestjs/swagger';
import { UserDto } from './user.dto';
@Get()
@ApiOkResponse({
type: UserDto,
description: 'Successfully retrieved users',
isArray: true,
})
findAll(): UserDto[] {
return [{ id: 1, name: 'John Doe' }];
}
adding-examples (swagger.io/docs)
In @nestjs/swagger
, you can add examples to response decorators using the @ApiResponse
, @ApiOkResponse
, @ApiCreatedResponse
, etc., by specifying the content property. The content property allows you to define examples inside the response schema.
Example:
import { Controller, Get } from '@nestjs/common';
import { ApiOkResponse, ApiResponse } from '@nestjs/swagger';
@Controller('users')
export class UserController {
@Get()
@ApiOkResponse({
description: 'Successfully retrieved user list',
content: {
'application/json': {
example: [
{
id: '123',
username: 'john_doe',
email: 'john@example.com',
},
{
id: '456',
username: 'jane_doe',
email: 'jane@example.com',
},
],
},
},
})
getUsers() {
return [
{
id: '123',
username: 'john_doe',
email: 'john@example.com',
},
{
id: '456',
username: 'jane_doe',
email: 'jane@example.com',
},
];
}
}
Adding Multiple Examples:
If you want multiple named examples, you can use the examples field:
import { Controller, Get } from '@nestjs/common';
import { ApiOkResponse } from '@nestjs/swagger';
@Controller('users')
export class UserController {
@Get()
@ApiOkResponse({
description: 'Successfully retrieved user',
content: {
'application/json': {
examples: {
adminUser: {
summary: 'Admin user example',
description: 'An example of an admin user',
value: {
id: '1',
username: 'admin_user',
role: 'admin',
email: 'admin@example.com',
},
},
regularUser: {
summary: 'Regular user example',
description: 'An example of a regular user',
value: {
id: '2',
username: 'regular_user',
role: 'user',
email: 'user@example.com',
},
},
},
},
},
})
getUserExample() {
return {
id: '1',
username: 'admin_user',
role: 'admin',
email: 'admin@example.com',
};
}
}
@ApiProperty
Defines properties inside DTOs.
import { ApiProperty } from '@nestjs/swagger';
export class UserDto {
@ApiProperty({ example: 1 })
id: number;
@ApiProperty({ example: 'John Doe' })
name: string;
}
@ApiParam
Describes path parameters.
import { ApiParam } from '@nestjs/swagger';
@Get(':id')
@ApiParam({ name: 'id', required: true, description: 'User ID', example: 1 })
findOne(@Param('id') id: string) {
return { id, name: 'John Doe' };
}
@ApiConsumes
Specifies the content type an endpoint accepts.
import { ApiConsumes } from '@nestjs/swagger';
@Post('upload')
@ApiConsumes('multipart/form-data')
upload(@UploadedFile() file: Express.Multer.File) {
return { filename: file.originalname };
}
@ApiCreatedResponse
Indicates a successful resource creation response.
import { ApiCreatedResponse } from '@nestjs/swagger';
@Post()
@ApiCreatedResponse({ description: 'User successfully created', type: UserDto })
create(@Body() user: UserDto) {
return user;
}
@ApiQuery
쿼리 파라메터의 타입을 정의할 때 사용합니다.
@ApiQuery({
name: 'academyId',
description: '하나의 business-info를 쿼리할 때 사용합니다.',
required: false,
})
async getBusinessInfoByAcademyId(
@Query('academyId') academyId?: string,
) {
return academyId;
}
Generating Swagger JSON
To generate the Swagger JSON schema:
const document = SwaggerModule.createDocument(app, config);
console.log(JSON.stringify(document, null, 2));
Conclusion
This cheatsheet covers the most commonly used decorators in @nestjs/swagger
for building well-documented APIs. Integrate them properly to provide clear and structured API documentation.